# -*- coding: utf-8 -*-

import cgi
import cStringIO as StringIO
import os
import sys
import logging
import urllib
import urllib2

sys.path.insert(0, "%s/../common/zip_packages/reportlab.zip" % os.path.dirname(__file__))
sys.path.insert(0, "%s/../common/zip_packages/html5lib.zip" % os.path.dirname(__file__))
sys.path.insert(0, "%s/../common/zip_packages/pyPdf.zip" % os.path.dirname(__file__))
sys.path.insert(0, "%s/../common/zip_packages/xhtml2pdf.zip" % os.path.dirname(__file__))
# sys.path.insert(0, "/Library/Python/2.5/site-packages/PIL")

import xhtml2pdf.ho.pisa as pisa

from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
# from django.template.loader import render_to_string
from django.views.generic.create_update import create_object, delete_object, \
                                                                update_object
from django.views.generic.list_detail import object_list, object_detail

from ragendja.template import render_to_string

from google.appengine.api import images
from google.appengine.api import urlfetch

from reports.models import DeseaseReport
from reports.forms import ReportForm

from django.utils import simplejson as json

from metaweb import get_domain_used, get_bioventurist_domain, \
                                                            process_write_multi

def disease_pipeline_report_page(request, topic_id):
    
    sys.stderr.write('disease_pipeline_report: '+ topic_id + '\n')
    
    report = DeseaseReport.all().filter("slug =", topic_id).get()
    
    data = {
        'bioventurist_domain': get_bioventurist_domain(),
        'domain_used': get_domain_used(),
        'report_name': 'disease_pipeline',
        'report': report,
        'topic_id': topic_id,
    }
    return render_to_response('disease_pipeline_report.html', data, 
                                    context_instance=RequestContext(request))


def disease_pipeline_report_edit_page(request, topic_id):
    
    sys.stderr.write('disease_pipeline_report: '+ topic_id + '\n')
    
    report = DeseaseReport.all().filter("slug =", topic_id).get()
    
    data = {
        'bioventurist_domain': get_bioventurist_domain(),
        'domain_used': get_domain_used(),
        'report_name': 'disease_pipeline',
        'report': report,
        'topic_id': topic_id,
    }
    return render_to_response('disease_pipeline_report_edit.html', data, 
                                    context_instance=RequestContext(request))
    
def overview_update(request, topic_id):
    
    report = DeseaseReport.all().filter("slug =", topic_id).get()
    
    if report is None:
        report = DeseaseReport(slug=topic_id)
        report.put()
    
    if request.method == "POST":
        try:
            key = request.POST.keys()[0]
        except Exception, e:
            return HttpResponse(json.dumps(dict(ok=False, error=e.message)))
        else:
            data = {
                "overview": request.POST.get(key, ""),
            }
            form = ReportForm(data=data)
            if form.is_valid():
                text = form.save(report, key)
                text = render_to_string(request, "html_render.html", {"text": text})
                response = HttpResponse(json.dumps(dict(ok=True, text=text)))
                return response
            else:
                form = render_to_string(request, "form_render.html", {"form":form,"id":key,})
                response = HttpResponse(json.dumps(dict(ok=False, form=form)))
                return response
    else:
        id = request.GET.get("field", "")
        
        try:
            overview = getattr(report, id)
        except AttributeError:
            overview = ""
            
        form = ReportForm(id=id, initial={"overview": overview,})
        data = {
            "id": id,
            "text": overview,
            "form": form,
        }
        form = render_to_string(request, "form_render.html", data)
        response = HttpResponse(json.dumps(dict(ok=True, text=overview, form=form)))
        return response
        

def convert_images(request):
    
    if request.method == "GET":
        
        url = urllib.unquote(request.GET["src"])
        
        from urlparse import urlsplit, urlunsplit
        scheme, netloc, path, query, frag = urlsplit(url)
        
        l = query.split("&")
        d = {}
        for kw in l:
            kw1, kw2 = kw.split("=")
            d[kw1] = kw2
            
        response = urlfetch.fetch(url=urlunsplit((scheme, netloc, path, "", "")), payload=urllib.urlencode(d), method=urlfetch.POST)

        image = images.Image(response.content)
        image.resize(image.width, image.height)
        thumb = image.execute_transforms(output_encoding=images.JPEG)
        response = HttpResponse(thumb, mimetype="image/jpeg")
        return response
    
def report2pdf(request, report_name):
    
    if request.method == 'POST':
        
        result = StringIO.StringIO()
        
        data = {
            "html": request.POST.get("html", ""),
        }
        
        html = render_to_string(request, "%s_4pdf.html" % (report_name,), data)
        pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result)
        if not pdf.err:
            response = HttpResponse(result.getvalue(), mimetype='application/pdf')
            response['Content-Disposition'] = 'attachment; filename=%s.pdf' % (report_name,)
            return response
        
        return HttpResponse('We had some errors<pre>%s</pre>' % cgi.escape(html))
    else:
        logging.error(' '+ 'GET');
        html = "<html><body>Sorry, GET not supported</body></html>"
        return HttpResponse(html)
        
def report_page(request):   
    
    sys.stderr.write('report main page\n');
    
    data = {
        'bioventurist_domain': get_bioventurist_domain(),
        'domain_used': get_domain_used(),
    }
    return render_to_response('report_main.html', data,
                                    context_instance=RequestContext(request))
